package com.mutouren.common.session.impl;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import com.mutouren.common.cache.RedisCache;
import com.mutouren.common.cache.impl.CacheManager;
import com.mutouren.common.log.LogAlias;
import com.mutouren.common.log.LogManager;
import com.mutouren.common.log.Logger;
import com.mutouren.common.session.Session;
import com.mutouren.common.session.SessionConfig;
import com.mutouren.common.session.UserInfo;
import com.mutouren.common.utils.CookieUtils;
import com.mutouren.common.utils.JsonUtils;
import com.mutouren.common.utils.StringUtils;

public class RemoteSessionImpl  implements Session{
	
	private static Logger errorLogger = LogManager.getLogger(LogAlias.SystemError.name());
	
	private static RedisCache cache = CacheManager.getRedisCache();
	private final static String keyFormat = "mtrsession_%s";
	
	private String buildKey(String sourceKey) {
		return String.format(keyFormat, sourceKey);
	}
	
	private String encoding(UserInfo userInfo) {
		return JsonUtils.beanToJson(userInfo);
	}
	
	private UserInfo decoding(String value) {
		return JsonUtils.JsonToBean(value, UserInfo.class);
	}	

	@Override
	public UserInfo get(HttpServletRequest request) {
		UserInfo result = null;
		
		String sessionId = CookieUtils.get(request, SessionConfig.cookieName);
		if (StringUtils.isNullOrEmpty(sessionId)) return null; 
		
		String strUser = cache.getString(buildKey(sessionId));
		if (strUser == null) return null;		
		result = decoding(strUser);
		
		long runTime = (new Date().getTime() - result.getLoginTime()) / 1000;
		if (runTime > SessionConfig.sessionMaxTime) {
			cache.delete(buildKey(sessionId)); // not do cookie
			return null;
		}
		
		try {
			cache.expire(buildKey(sessionId), SessionConfig.sessionTime);
		} catch (Throwable t) {
			errorLogger.error("RemoteSessionImpl cache.expire error", t);
		}
		
		return result;
	}

	@Override
	public void set(HttpServletRequest request, String sessionId, UserInfo userInfo) {
		cache.set(buildKey(sessionId), SessionConfig.sessionTime, encoding(userInfo));
	}

	@Override
	public void delete(HttpServletRequest request) {
		String sessionId = CookieUtils.get(request, SessionConfig.cookieName);
		if (StringUtils.isNullOrEmpty(sessionId)) return;
		
		cache.delete(buildKey(sessionId));
	}

}
